//
//  LBWStatusViewModel.swift
//  weibo
//
//  Created by Limonwei on 15/12/9.
//  Copyright © 2015年 heima. All rights reserved.
//

//对应cell

import UIKit

//LBWStatus里面需要处理逻辑的代码放在这里
class LBWStatusViewModel: NSObject {
    
    var status: LBWStatus? {
        didSet{
            
        }
    }
    
    //会员图标
    var vipImage: UIImage? {
        
        //判断用户的等级 根据不同个等级返回对应的会员图标
        guard let mbrank = status?.user?.mbrank else {
            return nil
        }
        if mbrank > 0 && mbrank < 7 {
            return UIImage(named: "common_icon_membership_level\(mbrank)")
        }
        return nil
        
    }
    
    //认证的图标
    // 认证类型 -1：没有认证; 1:认证用户，2,3,5: 企业认证，220: 达人
    var verifiedImage: UIImage? {
        guard let verified = status?.user?.verified else {
            return nil
        }
        switch verified {
        case 1:
            return UIImage(named: "avatar_vip")
            
        case 2,3,5:
            return UIImage(named: "avatar_enterprise_vip")
            
        case 220:
            return UIImage(named: "avatar_grassroot")
            
        default:
            return nil
        }
    }
    
    //三个按钮的字符串
    var retweetCountStr: String = "转发"
    var commentCountStr: String = "评论"
    var attitudeCountStr: String = "赞"
    
    //记录转发微博的内容
    var retweetText: String?
    
    //记录来源字符串
    var sourceText: String?
    
    //记录创建时间
    var creatAtText: String{
        
        guard let creatDate = NSDate.sinaDate(status!.created_at!) else{
            return ""
        }
        return creatDate.sinaDateString
    }
    
    //原创转发微博的富文本
    var originalStatusAttr: NSMutableAttributedString?
    var retweetedStatusAttr: NSMutableAttributedString?
    
    //原创转发微博特殊字符范围
    var originalLinkResults: [LBWMatchResult]?
    var retweetedLinkResults: [LBWMatchResult]?
    
    init(status: LBWStatus) {
        super.init()
        
        self.status = status
        
        retweetCountStr = getCountString(self.status?.reposts_count ?? 0, defaulTitle: "转发")
        commentCountStr = getCountString(self.status?.comments_count ?? 0, defaulTitle: "评论")
        attitudeCountStr = getCountString(self.status?.attitudes_count ?? 0, defaulTitle: "赞")
        
        //转发微博内容的逻辑 有@昵称+内容显示
        
        if let retweetStatus = status.retweeted_status {
            
            if let name = retweetStatus.user?.name {
                
                retweetText = "@\(name):\(retweetStatus.text!)"
                
                //处理转发微博特殊字符
                let result = dealStatusText(retweetText)
                retweetedStatusAttr = result.attr
                retweetedLinkResults = result.linkResult
                
            }
        }
        
        //来源字符串 判断source是否存在
        if let source = status.source where source.containsString("\">"){
            
            let startRange = source.rangeOfString("\">")!
            let endRange = source.rangeOfString("</")!
            
            sourceText = "来自\(source.substringWithRange(startRange.endIndex..<endRange.startIndex))"
        }
        
        //处理原创微博特殊字符
        let result = dealStatusText(status.text)
        originalStatusAttr = result.attr
        originalLinkResults = result.linkResult
        
        
    }
    
    //处理微博内容,通过表情字符串生成表情对应的富文本+
    private func dealStatusText(statusText: String?) -> (attr:NSMutableAttributedString?, linkResult: [LBWMatchResult]?){
        
        guard let text = statusText else{
            return (nil,nil)
        }
        //1.创建一个NSMutableAttributedString
        let result = NSMutableAttributedString(string: text)
        //2.匹配表情字符串
        //定义匹配结果数组
        var matchResults = [LBWMatchResult]()
        
        (text as NSString).enumerateStringsMatchedByRegex("\\[[a-zA-Z0-9\\u4e00-\\u9fa5]+\\]") { (captureCount, captureString, captureRange, _) -> Void in
            //生成结果
            let matchRes = LBWMatchResult(string: captureString.memory! as String, range: captureRange.memory)
            matchResults.append(matchRes)
        }
        //在这个地方拿着结果倒着遍历
        for matchResult in matchResults.reverse() {
            if let emoticon = LBWEmoticonTools.shareTools.emoticonWithChs(matchResult.string){
                //通过 emoticon 生成表情的 NSAttributeString
                let attachment = LBWTextAttachment()
                //通过表情模型生成attr
                let attr = attachment.attributedStringWithEmoticon(emoticon, font: UIFont.systemFontOfSize(LBWContentFont))
                
                //替换result对应位置的attr
                result.replaceCharactersInRange(matchResult.range, withAttributedString: attr)
            }
        }
        //添加特殊字符颜色
        let linkResult = addLinkColor(result)
        
        //添加字体大小的属性
        result.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(LBWContentFont), range: NSMakeRange(0, result.length))
        
        return (result,linkResult)
    }
    
    //添加特殊字符颜色
    private func addLinkColor(attr:NSMutableAttributedString) -> [LBWMatchResult]{
        //特殊字符的范围结果
        var result = [LBWMatchResult]()
        
        //匹配@xx
        (attr.string as NSString).enumerateStringsMatchedByRegex("@[^\\W]+") { (_, captureString, cputureRange, _) -> Void in
            attr.addAttribute(NSForegroundColorAttributeName, value: RGB(red: 80, green: 125, blue: 175), range: cputureRange.memory)
            result.append(LBWMatchResult(string: captureString.memory! as String, range: cputureRange.memory))
        }
        //匹配链接
        (attr.string as NSString).enumerateStringsMatchedByRegex("http://[^\\s^\\u4e00-\\u9fa5]+") { (_, captureString, cputureRange, _) -> Void in
            attr.addAttribute(NSForegroundColorAttributeName, value: RGB(red: 80, green: 125, blue: 175), range: cputureRange.memory)
            result.append(LBWMatchResult(string: captureString.memory! as String, range: cputureRange.memory))
        }
        // 匹配话题
        (attr.string as NSString).enumerateStringsMatchedByRegex("#[^#]+#") { (_, captureString, cputureRange, _) -> Void in
            attr.addAttribute(NSForegroundColorAttributeName, value: RGB(red: 80, green: 125, blue: 175), range: cputureRange.memory)
            result.append(LBWMatchResult(string: captureString.memory! as String, range: cputureRange.memory))
        }
        return result

    }
    
    
    //获取转发评论赞的字符串
    private func getCountString(count: Int, defaulTitle: String) -> String {
        if count > 0 {
            
            if count < 10000 {
            
            return "\(count)"
        }else{
            let result = CGFloat(count / 1000) / 10
            
            let resultStr = "\(result)万"
            
            if resultStr.containsString(".0") {
                return resultStr.stringByReplacingOccurrencesOfString(".0", withString: "")
            }
            return resultStr
        }
    }
        
        return defaulTitle
    }
    
    override var description: String {
        
        let keys = ["status"]
        
        return dictionaryWithValuesForKeys(keys).description
    }
    

}
























